package net.hackbard.piratenradio;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import com.spoledge.aacdecoder.AACPlayer;
import com.spoledge.aacdecoder.PlayerCallback;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Spinner;

public class Radio extends Activity implements PlayerCallback, View.OnClickListener{

	private static final String SERVER	= "http://api.piraten-radio.net/";
	private static final Integer BUFFER	= 5000; // in ms
	
	
	
	private ImageButton playButton;
	private ImageButton stopButton;
	private ImageButton webButton;
	private WebView 	InfoScrean;
	
	private TextView 	  textStreamed;
	private ImageView 	  splash;
	private LinearLayout  splach_src;
	private TextView 	  splach_text;
	private Spinner 	  Channel;
	
	private NotificationManager mNotificationManager;
	private Notification 		notification;
	private Intent 				notificationIntent;
	private PendingIntent 		contentIntent;
	
	private AACPlayer 	aacPlayer;
	private Handler 	uiHandler;
	
	private String channel_url[];
	private String channel_name[];
	private String channel_mp[];	
	
	private static final int STOPSPLASH = 1000;
	private static final int SPLASHTIME =  500;
	private static final int UPDATE 	= 3001;

	
	
	private static JSONArray getJSONfromURL(String url){

		//initialize
		InputStream is = null;
		String result = "";
		JSONArray jArray = null;

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		}catch(Exception e){
			Log.e("getJSONfromURL", "Error in http connection "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			Log.e("getJSONfromURL", "Error converting result "+e.toString());
		}

		//try parse the string to a JSON object
		try{
	        jArray = new JSONArray(result);
		}catch(JSONException e){
			Log.e("getJSONfromURL", "Error parsing data "+e.toString());
		}

		return jArray;
	}
		
	
	private void InfoUpdate(){
		String mp = "";
		
		try {
			mp = channel_mp[Channel.getSelectedItemPosition()];
		} catch (Exception e) {
			// Ignore
		}

		if (mp.length() == 0){
			InfoScrean.loadData("<html style='background-color:#000000; color:#FFFFFF'>Es sind leider keine Infos verf&uuml;gbar</html>", "text/html", null);
		}else{
			InfoScrean.loadUrl(SERVER+"1/now/"+mp+".html?BG_COLOR=000000&TEXT_COLOR=FFFFFF&BIG_COLOR=FF8800");
		}
	}
	
	private Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			Message msgnew;
			msgnew = new Message();
			switch (msg.what) {
			case STOPSPLASH:
				
				Playliste();
				
				splash.setImageResource(R.drawable.splash_2);
				msgnew.what = 1001;
				myHandler.sendMessageDelayed(msgnew, SPLASHTIME);	
				break;
			case 1001:
				splash.setImageResource(R.drawable.splash_3);
				msgnew.what = 1002;
				myHandler.sendMessageDelayed(msgnew, SPLASHTIME);	
				break;
			case 1002:
				splash.setImageResource(R.drawable.splash_4);
				msgnew.what = 1003;
				myHandler.sendMessageDelayed(msgnew, SPLASHTIME);	
				break;
			case 1003:
				msgnew.what = 1004;
				myHandler.sendMessageDelayed(msgnew, SPLASHTIME);	
				break;				
			case 1004:
				splach_src.setVisibility(View.GONE);
				break;
				
			case UPDATE:
				InfoUpdate();
				
				msgnew.what = UPDATE;
				myHandler.sendMessageDelayed(msgnew, 5000);	
				break;
			}
			
			super.handleMessage(msg);
		}
	};
	
	
	private void Playliste(){
		JSONArray liste = getJSONfromURL(SERVER+"1/list/aacp.json");
		
		long sel = 0;
		String olds = "";
		if (channel_url != null){
			sel = Channel.getSelectedItemId();
			olds = channel_url[Channel.getSelectedItemPosition()];
		}
		
		if (liste == null){
			channel_name	= new String[1];
			channel_url 	= new String[1];
			channel_mp		= new String[1];
			
			channel_name[0] = "Kein Internet";
			channel_url[0]	= "";
			channel_mp[0]	= "";
			
			sel = 0;
		}else{
			try {
				channel_name=new String[liste.length()];
				channel_url =new String[liste.length()];
				channel_mp	=new String[liste.length()];
				for (int i = 0; i < liste.length(); i++){
						channel_url [i] = liste.getJSONObject(i).getString("url");
						channel_name[i] = liste.getJSONObject(i).getString("name");
						channel_mp	[i] = liste.getJSONObject(i).getString("mp");
						
						if (olds == channel_url [i]){
							sel = i;
						}
				}
		
			} catch (Exception e1) {
				e1.printStackTrace();
				channel_name	= new String[1];
				channel_url 	= new String[1];
				channel_mp		= new String[1];
				
				channel_name[0] = "Fehler beim Laden der Liste";
				channel_url[0]	= "";
				channel_mp[0]	= "";
				
				sel = 0;
			}
		}
		
		ArrayAdapter<Object> adapter = new ArrayAdapter<Object>(this, android.R.layout.select_dialog_item, channel_name);
		Channel.setAdapter(adapter);
		try{
			Channel.setSelection((int) sel);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);

		playButton 		= (ImageButton) findViewById(R.id.button_play);
		stopButton 		= (ImageButton) findViewById(R.id.button_stop);
		webButton 		= (ImageButton) findViewById(R.id.button_web);
		InfoScrean		= (WebView) 	findViewById(R.id.InfoScrean);  
		textStreamed 	= (TextView) 	findViewById(R.id.info);	
		splash 			= (ImageView) 	findViewById(R.id.splashscreen);
		splach_src		= (LinearLayout)findViewById(R.id.splash_scr);
		splach_text 	= (TextView) 	findViewById(R.id.splash_text);
		Channel 		= (Spinner) 	findViewById(R.id.channel);
		
		try {
			PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			splach_text.setText("Version "+pinfo.versionName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		splash.setImageResource(R.drawable.splash_1);
		splach_src.setVisibility(View.VISIBLE);
		
		InfoScrean.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		InfoScrean.setBackgroundColor(0);
		
		mNotificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationIntent 	= new Intent(this, Radio.class);
		contentIntent 		= PendingIntent.getActivity(this, 0, notificationIntent, 0);
		
		Message msg = new Message();
		msg.what = STOPSPLASH;
		myHandler.sendMessageDelayed(msg, SPLASHTIME * 4);

		msg = new Message();
		msg.what = UPDATE;
		myHandler.sendMessageDelayed(msg, 100);		
		
		uiHandler 		= new Handler();
		
		playButton.setOnClickListener(this);
		stopButton.setOnClickListener(this);
		webButton.setOnClickListener(this);
	}

	public boolean onCreateOptionsMenu(Menu menu){ 
		menu.add(0,1,0,"Kontakt"); 
		menu.add(0,2,0,"Reload");
		menu.add(0,3,0,"Exit");
		return true; 
	}
	
	public boolean onOptionsItemSelected (MenuItem item){ 
		Uri uri = null;
		Intent intent = null;
		switch (item.getItemId()){ 
			case 1: 
				uri = Uri.parse("http://piraten-radio.net/impressum");
				intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);				
				return true;
			case 2:
				Playliste();
				InfoUpdate();
				return true;
			case 3:
				this.finish();
				return true;
		} 	
		return false; 
	}


	public void playerStarted() {
		uiHandler.post( new Runnable() {
            public void run() {
				mNotificationManager.cancelAll();
				notification 		= new Notification(R.drawable.control_play, "Verbinde zum Nerdpol", System.currentTimeMillis());
				notification.setLatestEventInfo(getApplicationContext(), "Live vom Nerdpol", channel_name[Channel.getSelectedItemPosition()], contentIntent);
				notification.flags = Notification.FLAG_NO_CLEAR;
				mNotificationManager.notify(1, notification);
				
				textStreamed.setText("Stream gestartet");
            }
        });
	}


	public void playerPCMFeedBuffer(final boolean isPlaying, final int audioBufferSizeMs,
			final int audioBufferCapacityMs) {
		uiHandler.post( new Runnable() {
            public void run() {
            	if (isPlaying){
            		textStreamed.setText("Play (Puffer: "+(audioBufferCapacityMs/1000)+"s)");
            	}
            }
        });
	}


	public void playerStopped(int perf) {
		uiHandler.post( new Runnable() {
            public void run() {
            	mNotificationManager.cancelAll();
            	textStreamed.setText("Gestoppt");
            }
        });
	}


	public void playerException(Throwable t) {
		uiHandler.post( new Runnable() {
            public void run() {
            	textStreamed.setText("Verbindungfehler :(");
            	mNotificationManager.cancelAll();
            }
        });
		t.printStackTrace();
	}


	public void onClick(View v) {
        switch (v.getId()) {
           case R.id.button_play: start(); break; 
           case R.id.button_stop: stop(); break;
           case R.id.button_web:
	              	Uri uri = Uri.parse("http://piraten-radio.net");
	   				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
	   				startActivity(intent);
   				break;
		   default:
			   break;
        }
        
    }
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		if (aacPlayer != null) {
            aacPlayer.stop();
            aacPlayer = null;
        }
	}
        
    public void start(){
		String streamUrl = channel_url[Channel.getSelectedItemPosition()];
		textStreamed.setText("Verbindungsaufbau...");
		
		Channel.setEnabled(false);
		playButton.setEnabled(false);
		
		if (aacPlayer != null) {
            aacPlayer.stop();
            aacPlayer = null;
        }
		aacPlayer = new AACPlayer(this,BUFFER,700);
        aacPlayer.playAsync(streamUrl);
    }
    
    public void stop(){
		Channel.setEnabled(true);
		playButton.setEnabled(true);
		
		if (aacPlayer != null) {
            aacPlayer.stop();
            aacPlayer = null;
        }
    }
}